import { View } from "@tarojs/components";
import { AtButton, AtRadio } from "taro-ui";
import { useEffect, useState } from "react";
import Taro from "@tarojs/taro";
import GlobalFooter from "../../components/GlobalFooter";
import questions from "../../data/questions.json";
import "./index.scss";

/**
 * 做题页面
 */
export default () => {
  //当前题目序号 从1开始
  const [current, setCurrent] = useState<number>(1);
  //当前题目状态
  const [currentQuestion, setCurrentQuestion] = useState(questions[0]);
  //当前答案
  const [currentAnswer, setCurrentAnswer] = useState<string>();
  //记录所有答案
  const [answerList] = useState<string[]>([]);
  //题目
  const questionOptions = currentQuestion.options.map((option) => {
    return { label: `${option.key}.${option.value}`, value: option.key };
  });
  //驱动 序号变化时驱动题目一起发生变化
  useEffect(() => {
    setCurrentQuestion(questions[current - 1]);
    setCurrentAnswer(answerList[current - 1]);
  }, [current]);
  return (
    <View className="doQuestionPage">
      <View className="at-article__h2 title">
        {current}、{currentQuestion.title}
      </View>
      <AtRadio
        options={questionOptions}
        value={currentAnswer}
        //选中选项时
        onClick={(value) => {
          //凸显当前选中答案
          setCurrentAnswer(value);
          //保存当前答案
          answerList[current - 1] = value;
        }}
      />
      ;{/*<Image src={header} />*/}
      {current < questions.length && (
        <AtButton
          type="primary"
          circle
          className="controlBtn"
          onClick={() => setCurrent(current + 1)}
          disabled={!currentAnswer}
        >
          下一题
        </AtButton>
      )}
      {current == questions.length && (
        <AtButton
          type="primary"
          circle
          className="controlBtn"
          disabled={!currentAnswer}
          onClick={() => {
            //传递答案
            Taro.setStorageSync("answerList", answerList);
            Taro.navigateTo({
              url: "/pages/result/index",
            });
          }}
        >
          查看结果
        </AtButton>
      )}
      {current > 1 && (
        <AtButton
          circle
          className="controlBtn"
          onClick={() => setCurrent(current - 1)}
        >
          上一题
        </AtButton>
      )}
      <GlobalFooter />
    </View>
  );
};
